package com.app.utils.util.view.expression.view;

import android.content.Context;
import android.text.SpannableString;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.EditText;

import com.app.utils.util.view.expression.ExpressionUtil;

/**
 * 显示表情的编辑框
 * Created by xuxinghai on 2016/8/9.
 */
public class BiaoQinEditView extends EditText {
    public BiaoQinEditView(Context context) {
        super(context);
    }

    public BiaoQinEditView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public BiaoQinEditView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 设置表情字符
     *
     * @param text
     */
    public void setPicText(CharSequence text) {

        try {
            SpannableString spannableString = ExpressionUtil.getExpressionString(getContext(), text);
            setText(spannableString);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除文字
     */
    public void delText() {
        int selectionStart = this.getSelectionStart();// 获取光标的位置
        if (selectionStart > 0) {
            String body = this.getText().toString();
            if (!TextUtils.isEmpty(body)) {
                String tempStr = body.substring(0, selectionStart);
                int i = tempStr.lastIndexOf(ExpressionUtil.delMacth);// 获取最后一个表情的位置
                if (i != -1) {
                    String cs = tempStr
                            .subSequence(i, selectionStart).toString();
                    // 如果是一个表情 则删除标表情
                    if (cs.toString().matches(ExpressionUtil.zhengze)) {
                        this.getEditableText().delete(i, selectionStart);
                        return;
                    }
                }
                //如果不是表情则删除最后一个字符
                this.getEditableText().delete(tempStr.length() - 1,
                        selectionStart);
            }
        }

    }
}
